package com.example.springstudy.controller;

import com.example.springstudy.common.PagedResultDto;
import com.example.springstudy.common.SuccessResult;
import com.example.springstudy.dto.DataEventInput;
import com.example.springstudy.entity.Ins;
import com.example.springstudy.services.InsRepository;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

// 数据报警控制器
@RestController
@RequestMapping("api/doc")
public class DocController {

    @GetMapping("month")
    public SuccessResult<String> getList() {

        ///2022月报.docx
        String fileName = "2022月报.docx";
        String staticPath = "static";
        try {
            URL inputUrl = new ClassPathResource("static/template-month.docx").getURL();
            URL outputUrl = new ClassPathResource(staticPath).getURL();
            String input = inputUrl.getPath();
            String output = outputUrl.getPath();
            XWPFDocument doc = new XWPFDocument(Files.newInputStream(Paths.get(input)));
            List<XWPFParagraph> xwpfParagraphList = doc.getParagraphs();
            //Iterate over paragraph list and check for the replaceable text in each paragraph
            for (XWPFParagraph xwpfParagraph : xwpfParagraphList) {
                for (XWPFRun xwpfRun : xwpfParagraph.getRuns()) {
                    String docText = xwpfRun.getText(0);
                    if (docText != null) {
                        if (docText.contains("${minTemp}")) {
                            docText = docText.replace("${minTemp}", "19");
                        }
                        if (docText.contains("${maxTemp}")) {
                            docText = docText.replace("${maxTemp}", "60");
                        }
                        xwpfRun.setText(docText, 0);
                    }
                }
            }

            // save the docs
            String outputFileName = Paths.get(output, fileName).toString();
            System.out.println("outputFileName = " + outputFileName);
            try (FileOutputStream out = new FileOutputStream(outputFileName)) {
                doc.write(out);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return new SuccessResult<>(fileName);
    }

}
